//
//  NEBaseTeamMemberRemoveController.swift
//  NETeamUIKit
//
//  Created by Laura on 2024/8/2.
//

import NEChatKit
import NECommonUIKit
import NECoreIM2Kit
import NECoreKit
import NIMSDK
import UIKit

@objcMembers
open class NEBaseTeamMemberRemoveController: NEBaseViewController, UITableViewDelegate,
                                             UITableViewDataSource, TeamMembersViewModelDelegate {
    /// 群id
    public var teamId: String?
    /// 群成员数据
    public var memberDatas: [NETeamMemberInfoModel]? {
        didSet {
            viewModel.setShowDatas(memberDatas)
        }
    }
    
    /// 创建者account id
    public var ownerId: String?
    
    public var isSenior = false
    
    public let backView = UIView()
    
    let viewModel = TeamMemberRemoveViewModel()
    
    /// 搜索输入控件
    public lazy var searchTextField: UITextField = {
        let field = UITextField()
        field.translatesAutoresizingMaskIntoConstraints = false
        field.placeholder = localizable("search_all")
        field.clearButtonMode = .always
        field.textColor = .ne_greyText
        field.font = UIFont.systemFont(ofSize: 14.0)
        field.backgroundColor = UIColor.white
        if let clearButton = field.value(forKey: "_clearButton") as? UIButton {
            clearButton.accessibilityIdentifier = "id.clear"
        }
        field.accessibilityIdentifier = "id.search"
        return field
    }()
    
    /// 群成员列表视图
    public lazy var contentTableView: UITableView = {
        let tableView = UITableView()
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.backgroundColor = .ne_backcolor
        tableView.dataSource = self
        tableView.delegate = self
        tableView.separatorColor = .clear
        tableView.separatorStyle = .none
        tableView.sectionHeaderHeight = 12.0
        tableView
            .tableFooterView =
        UIView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 12))
        tableView.keyboardDismissMode = .onDrag
        
        if #available(iOS 11.0, *) {
            tableView.estimatedRowHeight = 0
            tableView.estimatedSectionHeaderHeight = 0
            tableView.estimatedSectionFooterHeight = 0
        }
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0.0
        }
        return tableView
    }()
    
    /// 空占位图
    public lazy var emptyView: NEBaseContactEmptyView = {
        let view = NEBaseContactEmptyView(imageName: "icon_search_empty", content: localizable("no_result"), frame: .zero)
        view.translatesAutoresizingMaskIntoConstraints = false
        view.isUserInteractionEnabled = false
        view.isHidden = true
        return view
    }()
    
    /// 搜索背景图
    public lazy var searchIconImageView: UIImageView = {
        let searchIconImageView = UIImageView()
        searchIconImageView.image = coreLoader.loadImage("search_icon")
        searchIconImageView.translatesAutoresizingMaskIntoConstraints = false
        return searchIconImageView
    }()
    
    /// 搜索背景图
    public lazy var contactsBackView: UIView = {
        let backView = UIView()
        backView.translatesAutoresizingMaskIntoConstraints = false
        
        let imageView = UIImageView(image: coreLoader.loadImage("icon_contacts"))
        imageView.frame = CGRect(x: 15, y: 8, width: 20, height: 20)
        backView.addSubview(imageView)
        
        let label = UILabel(frame: CGRect(x: imageView.right+8, y: imageView.top, width: 200, height: imageView.height))
        label.text = "联系人"
        label.textColor = .normalTeamTipTitleColor
        label.font = NEConstant.defaultTextFont(14)
        backView.addSubview(label)
        
        return backView
    }()
    
    public init(teamId: String?) {
        super.init(nibName: nil, bundle: nil)
        self.teamId = teamId
    }
    
    public required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override open func viewDidLoad() {
        super.viewDidLoad()
        addObserver()
        viewModel.delegate = self
        viewModel.teamId = teamId
        
        navigationView.setMoreButtonTitle(localizable("member_select_sure"))
        navigationView.moreButton.titleLabel?.font = NEConstant.defaultTextFont(14)
        navigationView.moreButton.setTitleColor(.normalTeamOrangeColor, for: .normal)
        navigationView.moreButton.addTarget(self, action: #selector(sureRemove), for: .touchUpInside)
        
        weak var weakSelf = self
        if let tid = teamId {
            weakSelf?.viewModel.getTeamInfo(tid) { teamInfo, error in
                if error != nil {
                    weakSelf?.emptyView.isHidden = false
                    if let err = error {
                        weakSelf?.showToast(err.localizedDescription)
                    }
                } else {
                    weakSelf?.ownerId = teamInfo?.team?.ownerAccountId
                    if teamInfo?.team?.isDisscuss() == false {
                        weakSelf?.isSenior = true
                        weakSelf?.title = localizable("group_memmber_remove")
                    } else {
                        weakSelf?.title = localizable("group_memmber_remove")
                    }
                    if IMKitConfigCenter.shared.onlineStatusEnable {
                        if let members = teamInfo?.users {
                            var subcribeMembers = [NETeamMemberInfoModel]()
                            for model in members {
                                if let account = model.teamMember?.accountId {
                                    if account != IMKitClient.instance.account() {
                                        subcribeMembers.append(model)
                                    }
                                }
                            }
                            weakSelf?.viewModel.subcribeMembers(members) { error in
                                NEALog.infoLog(weakSelf?.className() ?? "", desc: "sub cribe members error : \(error?.localizedDescription ?? "")")
                            }
                        }
                    }
                    weakSelf?.didNeedRefreshUI()
                }
            }
        }
        setupUI()
        
//        NotificationCenter.default.addObserver(self, selector: #selector(appDidEnterBackground), name: UIApplication.didBecomeActiveNotification, object: nil)
    }
    
//    func appDidEnterBackground() {
//        self.contentTableView.reloadData()
//    }
    
    /// UI 初始化
    open func setupUI() {
//        backView.backgroundColor = .white
//        backView.translatesAutoresizingMaskIntoConstraints = false
//        backView.clipsToBounds = true
//        backView.layer.cornerRadius = 15.0
        
//        view.addSubview(backView)
//        NSLayoutConstraint.activate([
//            backView.topAnchor.constraint(equalTo: view.topAnchor, constant: topConstant + 7.0),
//            backView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: kScreenInterval),
//            backView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -kScreenInterval),
//            backView.heightAnchor.constraint(equalToConstant: 30),
//        ])
        
//        backView.addSubview(searchIconImageView)
//        NSLayoutConstraint.activate([
//            searchIconImageView.centerYAnchor.constraint(equalTo: backView.centerYAnchor),
//            searchIconImageView.leftAnchor.constraint(equalTo: backView.leftAnchor, constant: 16.0),
//        ])
        
//        backView.addSubview(searchTextField)
//        NSLayoutConstraint.activate([
//            searchTextField.leftAnchor.constraint(equalTo: backView.leftAnchor, constant: 36.0),
//            searchTextField.rightAnchor.constraint(equalTo: backView.rightAnchor, constant: -15.0),
//            searchTextField.topAnchor.constraint(equalTo: backView.topAnchor),
//            searchTextField.bottomAnchor.constraint(equalTo: backView.bottomAnchor),
//        ])
        
        
        view.addSubview(contactsBackView)
        NSLayoutConstraint.activate([
            contactsBackView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0.0),
            contactsBackView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0.0),
            contactsBackView.topAnchor.constraint(equalTo: view.topAnchor, constant: topConstant + 7.0),
            contactsBackView.heightAnchor.constraint(equalToConstant: 36),
        ])
        
        
        view.addSubview(contentTableView)
        NSLayoutConstraint.activate([
            contentTableView.leftAnchor.constraint(equalTo: view.leftAnchor),
            contentTableView.rightAnchor.constraint(equalTo: view.rightAnchor),
            contentTableView.topAnchor.constraint(equalTo: contactsBackView.bottomAnchor),
            contentTableView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
        ])
        
        contentTableView.register(NEBaseTeamMemberRemoveCell.self, forCellReuseIdentifier: "\(NEBaseTeamMemberRemoveCell.self)")
        
        view.addSubview(emptyView)
        NSLayoutConstraint.activate([
            emptyView.leftAnchor.constraint(equalTo: contentTableView.leftAnchor),
            emptyView.rightAnchor.constraint(equalTo: contentTableView.rightAnchor),
            emptyView.topAnchor.constraint(equalTo: contentTableView.topAnchor, constant: 50),
            emptyView.bottomAnchor.constraint(equalTo: contentTableView.bottomAnchor),
        ])
    }
    
    func addObserver() {
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(textChange),
            name: UITextField.textDidChangeNotification,
            object: nil
        )
    }
    
    func isOwner(_ userId: String?) -> Bool {
        if isSenior == false {
            return false
        }
        if let uid = userId, let oid = ownerId, uid == oid {
            return true
        }
        return false
    }
    
    func textChange() {
        viewModel.searchDatas.removeAll()
        if let text = searchTextField.text, text.count > 0 {
            for model in viewModel.datas {
                var searched = false
                
                if let teamName = model.atNameInTeam() {
                    if teamName.contains(text) {
                        searched = true
                        viewModel.searchDatas.append(model)
                    }
                }
                
                if !searched, let mobile = model.nimUser?.user?.mobile {
                    if mobile.contains(text) {
                        searched = true
                        viewModel.searchDatas.append(model)
                    }
                }
                
                if !searched {
                    if TeamHelper.userTitleName(model).contains(text) {
                        searched = true
                        viewModel.searchDatas.append(model)
                    }
                }
            }
        }
        
        didNeedRefreshUI()
    }
    
    func getRealModel(_ index: Int) -> NETeamMemberInfoModel? {
        if let text = searchTextField.text, text.count > 0 {
            return viewModel.searchDatas[index]
        }
        return viewModel.datas[index]
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    // MARK: UITableViewDelegate, UITableViewDataSource
    
    open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if let text = searchTextField.text, text.count > 0 {
            return viewModel.searchDatas.count
        }
        return viewModel.datas.count
    }
    
    open func tableView(_ tableView: UITableView,
                        cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if let cell = tableView.dequeueReusableCell(
            withIdentifier: "\(NEBaseTeamMemberRemoveCell.self)",
            for: indexPath
        ) as? NEBaseTeamMemberRemoveCell {
            if let model = getRealModel(indexPath.row) {
                if let accid = model.teamMember?.accountId {
                    cell.configure(model, selected: (viewModel.selectDic[accid] != nil))
                }else {
                    cell.configure(model, selected: false)
                }
                
                if isOwner(model.nimUser?.user?.accountId) {
                    cell.ownerLabel.isHidden = false
                    cell.ownerLabel.text = localizable("team_owner")
                } else if model.teamMember?.memberRole == .TEAM_MEMBER_ROLE_MANAGER {
                    cell.ownerLabel.isHidden = false
                    cell.ownerLabel.text = localizable("team_manager")
                } else {
                    cell.ownerLabel.isHidden = true
                }
                
                if IMKitConfigCenter.shared.onlineStatusEnable {
                    cell.headerView.alpha = 0.5
                    
                    if let account = model.nimUser?.user?.accountId {
                        if account == IMKitClient.instance.account() {
                            cell.headerView.alpha = 1.0
                        } else if let event = viewModel.onLineEventDic[account] {
                            if event.value == NIMSubscribeEventOnlineValue.login.rawValue {
                                cell.headerView.alpha = 1.0
                            }
                        }
                    }
                }
            }
            return cell
        }
        return UITableViewCell()
    }
    
    open func tableView(_ tableView: UITableView,
                        heightForRowAt indexPath: IndexPath) -> CGFloat {
        56.0
    }
    
    open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = !(searchTextField.text ?? "").isEmpty ? viewModel.searchDatas[indexPath.row] :  viewModel.datas[indexPath.row]
        if let accid = model.teamMember?.accountId {
            if viewModel.selectDic[accid] != nil {
                viewModel.selectDic[accid] = nil
            } else {
                viewModel.selectDic[accid] = model
            }
            contentTableView.reloadData()
            didChangeSelectMember()
        }
    }
    
    /// 选择成员变更回调，内部根据选择数量来做右上角状态变更
    func didChangeSelectMember() {
        if viewModel.selectDic.count > 0 {
            let title = localizable("member_select_sure") + "(\(viewModel.selectDic.count))"
            navigationView.moreButton.setTitle(title, for: .normal)
        } else {
            navigationView.moreButton.setTitle(localizable("member_select_sure"), for: .normal)
        }
    }
    
    open func selectedUserIds() -> [String] {
        return Array(viewModel.selectDic.keys)
    }
    
    open func deleteSuccess() {
        viewModel.removeModels(selectedUserIds())
        viewModel.selectDic.removeAll()
        didNeedRefreshUI()
    }
    
    /// 移除群成员
    open func sureRemove() {
        print("did click sure button")
        if viewModel.selectDic.count == 0 {
            return
        }
        weak var weakSelf = self
        showAlert(title: localizable("remove_manager_title"), message: localizable("remove_member_tip")) {
            if NEChatDetectNetworkTool.shareInstance.manager?.isReachable == false {
                weakSelf?.view.makeToast(commonLocalizable("network_error"))
                return
            }
            
            if let tid = weakSelf?.teamId, !weakSelf!.selectedUserIds().isEmpty {
                weakSelf?.viewModel.removeTeamMember(tid, weakSelf!.selectedUserIds()) { error in
                    if let err = error {
                        if err.code == noPermissionCode {
                            weakSelf?.view.makeToast(localizable("no_permission_tip"))
                        } else {
                            weakSelf?.view.makeToast(localizable("remove_failed"))
                        }
                    } else {
                        weakSelf?.deleteSuccess()
                    }
                }
            }
        }
    }
    
    func didNeedRefreshUI() {
        if let text = searchTextField.text, text.count > 0 {
            emptyView.isHidden = viewModel.searchDatas.count > 0
        } else {
            emptyView.isHidden = true
        }
        contactsBackView.isHidden = !emptyView.isHidden
        contentTableView.reloadData()
        didChangeSelectMember()
    }
    
    override open func didMove(toParent parent: UIViewController?) {
        super.didMove(toParent: parent)
        if IMKitConfigCenter.shared.onlineStatusEnable {
            if parent == nil {
                viewModel.unSubcribeMembers(viewModel.datas) { [weak self] error in
                    NEALog.infoLog(self?.className() ?? " ", desc: #function + " un sub scribe member error : \(error?.localizedDescription ?? "")")
                }
            }
        }
    }
}
